package org.example.myleet.preprocess;

import java.util.HashMap;
import java.util.Map;

public class PreprocessSolution {
    //p12

    private static Map<Integer, String> numRomanMap = new HashMap<>();
    static {
        numRomanMap.put(1, "I");
        numRomanMap.put(2, "II");
        numRomanMap.put(3, "III");
        numRomanMap.put(4, "IV");
        numRomanMap.put(5, "V");
        numRomanMap.put(6, "VI");
        numRomanMap.put(7, "VII");
        numRomanMap.put(8, "VIII");
        numRomanMap.put(9, "IX");
        numRomanMap.put(10, "X");
        numRomanMap.put(20, "XX");
        numRomanMap.put(30, "XXX");
        numRomanMap.put(40, "XL");
        numRomanMap.put(50, "L");
        numRomanMap.put(60, "LX");
        numRomanMap.put(70, "LXX");
        numRomanMap.put(80, "LXXX");
        numRomanMap.put(90, "XC");
        numRomanMap.put(100, "C");
        numRomanMap.put(200, "CC");
        numRomanMap.put(300, "CCC");
        numRomanMap.put(400, "CD");
        numRomanMap.put(500, "D");
        numRomanMap.put(600, "DC");
        numRomanMap.put(700, "DCC");
        numRomanMap.put(800, "DCCC");
        numRomanMap.put(900, "CM");
        numRomanMap.put(1000, "M");
        numRomanMap.put(2000, "MM");
        numRomanMap.put(3000, "MMM");
    }
    public String intToRoman(int num) {
        StringBuilder reply = new StringBuilder();
        int n = num;
        int base = 1000;
        while (n > 0) {
            int t = n / base * base;
            if (t > 0) {
                reply.append(numRomanMap.get(t));
            }
            n %= base;
            base /= 10;
        }
        return reply.toString();
    }

    //p13
    private static Map<String, Integer> ROMAN_TO_INT = new HashMap<>();
    static {
        ROMAN_TO_INT.put("IV", 4);
        ROMAN_TO_INT.put("IX", 9);
        ROMAN_TO_INT.put("XL", 40);
        ROMAN_TO_INT.put("XC", 90);
        ROMAN_TO_INT.put("CD", 400);
        ROMAN_TO_INT.put("CM", 900);
        ROMAN_TO_INT.put("I", 1);
        ROMAN_TO_INT.put("V", 5);
        ROMAN_TO_INT.put("X", 10);
        ROMAN_TO_INT.put("L", 50);
        ROMAN_TO_INT.put("C", 100);
        ROMAN_TO_INT.put("D", 500);
        ROMAN_TO_INT.put("M", 1000);
    }
    public int romanToInt(String s) {
        int len = s.length() - 1;
        int result = 0;
        int i = 0;
        for (; i < len; ++i) {
            char c1 = s.charAt(i);
            char c2 = s.charAt(i + 1);
            String key = new String(new char[]{c1, c2});
            if (ROMAN_TO_INT.containsKey(key)) {
                result += ROMAN_TO_INT.get(key);
                ++i;
            } else {
                result += ROMAN_TO_INT.get(new String(new char[]{c1}));
            }
        }
        if (i < s.length()) {
            char c1 = s.charAt(i);
            result += ROMAN_TO_INT.get(new String(new char[]{c1}));
        }
        return result;
    }
}
